package com.magupe.push.server.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.magupe.push.common.protocol.request.LoginRequestPacket;
import com.magupe.push.common.protocol.response.LoginResponsePacket;
import com.magupe.push.log.util.LogUtils;
import com.magupe.push.common.session.Session;
import com.magupe.push.server.utils.MapperUtils;
import com.magupe.push.server.utils.SessionUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket packet) throws Exception {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(packet.getVersion());
        loginResponsePacket.setSuccess(true);
        loginResponsePacket.setSecret(packet.getSecret());
        loginResponsePacket.setContentId(packet.getContentId());
        loginResponsePacket.setUserId(packet.getUserId());
        loginResponsePacket.setSource(packet.getSource());
        loginResponsePacket.setMsgId(packet.getMsgId());
        
		String contentId = packet.getContentId();
		String secret = packet.getSecret();
		String deviceId = packet.getDeviceId();
		String userId = packet.getUserId();
		
		if (valid(ctx, secret, contentId)) {
			LogUtils.processLog(ctx.channel(), packet, "移动端登录成功", false, null);
			
			/**
			 * 绑定用户和channel的关系
			 */
            SessionUtil.bindSession(new Session(secret, contentId, deviceId, userId), ctx.channel());
            
            /**
             * 绑定用户和ip地址及端口的关系(为负载均衡做准备)
             */
            MapperUtils.processMapper(userId, ctx.channel().localAddress().toString());
            
            // 登录响应
            ctx.channel().writeAndFlush(loginResponsePacket);	
        } else {
        	LogUtils.processLog(ctx.channel(), packet, "移动端登录失败", false, null);
        	
        	// 登录响应
        	loginResponsePacket.setSuccess(false);	
        	ctx.close();
        }
	}

	/**
	 * 读取secret和contentId在信息库中，看是否存在，该操作应当异步进行
	 * @param secret
	 * @param contentId
	 * @return
	 */
	private boolean valid(ChannelHandlerContext ctx, String secret, String contentId) {
		InputStream is = AuthenticationRequestHandler.class.getClassLoader().getResourceAsStream("data.txt");
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String str;
		try {
			str = br.readLine();
			JSONObject jsonObject = JSONObject.parseObject(str);
			JSONArray array = jsonObject.getJSONArray("list");
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = array.getJSONObject(i);
				map.put(object.getString("contentId"), object.getString("secret"));
			}
			if(map.get(contentId).equals(secret)) {
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
			LogUtils.processExceptionLog(ctx, e, "Authentication Valid");
		} finally {
			try {
				br.close();
				isr.close();
				is.close();
			} catch (IOException e) {e.printStackTrace();LogUtils.processExceptionLog(ctx, e, "Stream Close");}
		}

		return false;
	}
}
